<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <SmForm
      class="-mb-15px"
      ref="formRef"
      isCol
      label-width="150px"
      v-model="formData"
      v-loading="formLoading"
      :options="requestFormOptions"
      :getModelValue="getFormData"
    >
      <template #avatar>
        <MultiImageUpload
          v-model="formData.imgList1"
          :limit="1"
          @update:model-value="(val) => changeOneImg(val, formData, 'avatar')"
        />
      </template>
    </SmForm>

    <template #footer>
      <el-button @click="submitFormDB" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { createUser, getRoleList, getUser, updateUser } from "@/api/user";
import { addProperty } from "@/components/SmForm/src/utils";
import { createDBFn } from "@/utils/decorate";
import { defaultProps } from "@/utils/tree";
import { getDeptList, getDeptRoleList, getOrganizationList, getUserList } from "@/commonData";
import { phoneRules } from "@/commonData/rules";
import { enableList, genderList, userTypeList } from "@/commonData/dict";
import { changeOneImg } from "@/utils/changeData";
import EmployeeAPI from "@/api/org/employee";

/** 仓库 表单 */
defineOptions({ name: "OpenForm" });

const { t } = useI18n(); // 国际化

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref(""); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(""); // 表单的类型：create - 新增；update - 修改
const initFormData = () => {
  return {};
};
const formData: any = ref(initFormData());
const formRef = ref(); // 表单 Ref
const organizationList = ref([]);
const deptList = ref([]);
const roleList = ref([]);
const userList = ref([]);
const deptRoleList = ref([]);

const requestFormOptions: any = ref([]);
const createRequestFormOptions = () => {
  /**
   *  1-avatar-头像放后面-上传还有些问题-参照机构-等后端修复
   *  2-deptId-所属部门-1
   *  3-deptRoleIds-部门角色ID列表
   *  4-email-邮箱-1
   *  5-gender-性别-1
   *  6-name-姓名-1
   *  7-orgNo-所属机构编号-1
   *  8-password-密码-1
   *  9-phone-手机号-1
   *  10-position-职位-1
   *  11-status-状态 1:正常 0:禁用-1
   *  12-userId-1
   */

  const list = [
    {
      type: "select",
      placeholder: "用户",
      label: "用户",
      prop: "userId",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: userList,
    },
    {
      requiredFlag: true,
      type: "tree-select",
      placeholder: "归属机构",
      prop: "orgNo",
      label: "归属机构",
      attrs: {
        filterable: true,
        clearable: true,
        // data: mockTreeList,
        data: organizationList,
        // props: defaultProps,
        "check-strictly": true,
        // "node-key": "id",
      },
    },
    {
      type: "select",
      placeholder: "归属部门",
      label: "归属部门",
      prop: "deptId",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
        onChange: (val: any) => getDeptRoleList(deptRoleList, { deptId: val }),
      },
      children: deptList,
    },

    {
      type: "select",
      placeholder: "部门角色",
      label: "部门角色",
      prop: "deptRoleIds",
      attrs: {
        "collapse-tags": true,
        multiple: true,
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: deptRoleList,
    },
    {
      type: "input",
      label: "手机号",
      prop: "phone",
      placeholder: "手机号",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
      rules: phoneRules,
    },
    {
      type: "input",
      label: "员工名称",
      prop: "name",
      placeholder: "员工名称",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "input",
      label: "邮箱",
      prop: "email",
      placeholder: "邮箱",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "select",
      placeholder: "性别",
      label: "性别",
      prop: "gender",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: genderList,
    },
    {
      type: "input",
      label: "职位",
      prop: "position",
      placeholder: "职位",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "select",
      placeholder: "状态",
      label: "状态",
      prop: "status",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: enableList,
    },
    // {
    //   slot: "avatar",
    //   label: "头像",
    // },
  ];

  addProperty(list);
  return list;
};
requestFormOptions.value = createRequestFormOptions();

/** 打开弹窗 */
const open = async (type: string, userId?: string) => {
  dialogVisible.value = true;
  dialogTitle.value = t("action." + type);
  formType.value = type;
  resetForm();
  getOrganizationList(organizationList);
  getDeptList(deptList);
  getRoleList(roleList);
  getUserList(userList);
  // 修改时，设置数据
  if (userId) {
    formLoading.value = true;
    try {
      formData.value = await EmployeeAPI.getInfo(userId);
      // 主动触发表单数据回显
      formRef.value.initForm();
    } finally {
      formLoading.value = false;
    }
  }
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(["success"]); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as any;
    if (formType.value === "create") {
      await EmployeeAPI.create(data);
      // ElMessage.success("操作成功");
    } else if (formType.value === "update") {
      await EmployeeAPI.update(data.userId, data);
      // ElMessage.success("操作成功");
    }
    ElMessage.success("操作成功");
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit("success");
  } finally {
    formLoading.value = false;
  }
};
const submitFormDB = createDBFn(submitForm);

/** 重置表单 */
const resetForm = () => {
  formData.value = initFormData();
  formRef.value?.resetFields();
};

const getFormData = () => {
  return formData.value;
};
</script>
